//
//  FavouritesView.m
//  MobileZIPCodes
//
//  Created by Andreas Schwelling on 07.12.07.
//	http://www.andi.de/zipcodes/
// 
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.
//

#import "FavouritesView.h"





@implementation FavouritesView

- (id)initWithFrame:(struct CGRect)rect {
	
	
	
	
	self = [super initWithFrame:rect];
	_rect = rect;
	_navBar  = [[UINavigationBar alloc] init];
	[_navBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 48.0f)];
	[_navBar setDelegate:self];
	[_navBar enableAnimation];
	
	[_navBar pushNavigationItem: [[UINavigationItem alloc] initWithTitle: @"Favourites"]];	
	[_navBar showLeftButton:nil withStyle:2 rightButton:@"Edit" withStyle:0];
	
	[self addSubview:_navBar];
	
	_transitionView =  [ [ UITransitionView alloc ] 
						initWithFrame:
						CGRectMake(rect.origin.x, rect.origin.y+48.0f, rect.size.width,
								   rect.size.height - 48.0f)
						];
	[self addSubview:_transitionView];
	
	_sectionList = [[UISectionList alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-48.0f) showSectionIndex:NO];
	[_sectionList setDataSource:self];
	
	[_transitionView transition:0  toView:_sectionList];
	
	
	_table = [_sectionList table];
	[_table setShouldHideHeaderInShortLists:NO];
	UITableColumn * packageColumn = [[UITableColumn alloc] initWithTitle:@"Title" identifier:@"title" width:320.0f];
	
	[_table addTableColumn:packageColumn];
	[_table setSeparatorStyle:1];
	[_table setRowHeight:48.0f];
	[_table setDelegate:self];
	[_table setAllowsReordering:NO];
	
	[self fillTable];
	[_table reloadData];
	[_sectionList reloadData];
	
	_actualView = _sectionList;
	
	
	
	[_bdo release];
	_bdo = [[BrowseDataObject alloc] init];
	
	return self;
	
	
}

- (void) fillTable {
	
	DataManager *dm = [DataManager alloc];
	
	
	[_tableCells release];
	_tableCells = [[NSMutableArray alloc] init];
	
	[_tableHeaders release];	
	_tableHeaders = [[NSMutableArray alloc] init];
	
	[_tableEntries release];
	_tableEntries = [[NSMutableDictionary alloc] init];
	
	
	NSMutableArray *favCountries = [dm getFavouredEntriesCountries];
	
	int count = 0;
	
	int i=0;
	for (i=0;i<[favCountries count];i++) {	
		
		
		if (! [[dm getInstalledCountries] containsObject:[favCountries objectAtIndex:i]]) continue;
		
		if ([[dm getFavouredEntriesForCountry:[favCountries objectAtIndex:i]] count]<1) continue;
		
		NSMutableDictionary* cellDict = [[NSMutableDictionary alloc] initWithCapacity:2];
		[cellDict setObject:[favCountries objectAtIndex:i] forKey:@"title"];
		[cellDict setObject:[[NSNumber alloc] initWithInt:count] forKey:@"beginRow"];
		
		[_tableHeaders addObject: cellDict];
		
		NSDictionary *favsForCountry = [dm getFavouredEntriesForCountry:[favCountries objectAtIndex:i]];
		
		NSArray *cities = [favsForCountry allKeys];
		
		int j=0;
		for (j=0;j<[cities count];j++) {
			
			//NSLog(@"state: %@",[[favsForCountry objectForKey:[cities objectAtIndex:j]] objectForKey:@"state"]);
			
			NSMutableDictionary* entryContents = [[NSMutableDictionary alloc] initWithCapacity:3];
			[entryContents setObject:[cities objectAtIndex:j] forKey:@"city"];
			[entryContents setObject:[[favsForCountry objectForKey:[cities objectAtIndex:j]] objectForKey:@"state"] forKey:@"state"];
			[entryContents setObject:[favCountries objectAtIndex:i] forKey:@"country"];
			[_tableEntries setObject:entryContents forKey:[NSString stringWithFormat:@"%d",count]];
			[entryContents release];
			
			
			//NSLog(@"favsfc: %@",favsForCountry);
			
			UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
			[cell setTitle: [cities objectAtIndex:j]];
			[cell setDisclosureStyle:2];
			[cell setShowDisclosure:YES animated:NO];
			
			UIRightTextLabel *stateLable = [[UIRightTextLabel alloc] initWithFrame:CGRectMake(290.0f, 16.0f, 200.0f, 15.0f)];
			[stateLable setText:[[favsForCountry objectForKey:[cities objectAtIndex:j]] objectForKey:@"state"]];
			
			struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:13];
			float transparent[4] = {0, 0, 0, 0};
			[stateLable setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), transparent)];
			[stateLable setWrapsText:YES];
			[stateLable setFont:font];
			[stateLable realignText];
			[cell addSubview:stateLable];
			[stateLable release];
			
			
			[_tableCells addObject: cell]; 
			[cell release];
			count++;
		}
	}
	
	[dm release];
	//NSLog(@"_tableEntries: %@",_tableEntries);
	
	
}

-(void)dealloc {
	[_tableHeaders release];
	[_tableCells release];
	[_sectionList release];	
	[_navBar release];
	[_tableEntries release];
	[_transitionView release];
	
	[super dealloc];
}


-(BrowseDataObject*)getBdo {
	return _bdo;
}

-(UINavigationBar*)getNavBar {
	return _navBar;
}


-(void)setDelegate:(id)del {
	//NSLog(@"delegate: %@",del);
	_delegate = del;
}

-(UITransitionView*)getTransitionView {
	return _transitionView;
}

-(UIView*)getCurrentView {
	return _actualView;
}

-(void)setCurrentView:(UIView*)view {
	_actualView = view;
	//NSLog(@"setCurrentView: %@",view);
}

#pragma mark - delegate methods -


- (void)navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button {
	switch (button) {
		case 0:
			if (_editing) {
				[_navBar showLeftButton:nil withStyle:2 rightButton:@"Edit" withStyle:0];
				_editing = NO;
				[_table enableRowDeletion:NO animated:YES];
				[_sectionList reloadData];
				
			} else {
				[_navBar showLeftButton:nil withStyle:2 rightButton:@"Edit" withStyle:1];
				_editing = YES;
				[_table enableRowDeletion:YES animated:YES];
				[_sectionList reloadData];
				
				
			}
			break;
			case 1:
			//NSLog(@"navar button 1");
			//NSLog(@"actualView: %@",_actualView);
			//NSLog(@"prevView: %@",[_actualView getPrevView]);
			if ([_actualView getPrevView] == _sectionList) {
				[_navBar showLeftButton:nil withStyle:2 rightButton:@"Edit" withStyle:0];
			}
			[_transitionView transition:2 fromView:_actualView toView:[_actualView getPrevView]];
			
			_actualView = [_actualView getPrevView];
			//	if (_actualView == namezipview) _previousView = _sectionList;
			
			break;
	}
}


- (int)numberOfSectionsInSectionList:(UISectionList *)aSectionList {
	return [_tableHeaders count];
}

- (NSString *)sectionList:(UISectionList *)aSectionList titleForSection:(int)row {	
	return [[_tableHeaders objectAtIndex:row] objectForKey:@"title"];
}       

- (int)sectionList:(UISectionList *)aSectionList rowForSection:(int)row {
	// this is what determines the placement of the header
	return [[[_tableHeaders objectAtIndex:row] valueForKey:@"beginRow"] intValue];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
{
	return [_tableCells objectAtIndex: row];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
			   reusing: (BOOL) reusing
{
	//What does this message do?
    return nil;
}

- (int) numberOfRowsInTable: (UISectionTable*)table
{
	return [_tableCells count];
}

- (BOOL)table:(UITable*)table canDeleteRow:( int)row {
	return YES;
}

- (void)table:(UITable*)table deleteRow:(int)row {
	
	DataManager *dm = [DataManager alloc];
	
	[dm removeFavouredEntry:[[_tableEntries objectForKey:[NSString stringWithFormat:@"%d",row]] objectForKey:@"city"]  forCountry:[[_tableEntries objectForKey:[NSString stringWithFormat:@"%d",row]] objectForKey:@"country"]];
	
	[dm release];
	
	
	[self fillTable];
	[_sectionList reloadData];
}

- (void) tableRowSelected: (NSNotification*) notification 
{
	//Get selected cell and filename
	UIImageAndTextTableCell* selectedCell = [_tableCells objectAtIndex: [_table selectedRow]];
	//NSLog(@"seletedCell title: %@",[selectedCell title]);
	[_navBar showLeftButton:@"Back" withStyle:2 rightButton:nil withStyle:0];	
	
	UIView *_searchNameResultView = [SearchNameResultView alloc];
	
	//[_bdo setCountry:[selectedCell title]];
	
	[_searchNameResultView setCity:[[_tableEntries objectForKey:[NSString stringWithFormat:@"%d",[_table selectedRow]]] objectForKey:@"city"]];
	[_searchNameResultView setCountry:[[_tableEntries objectForKey:[NSString stringWithFormat:@"%d",[_table selectedRow]]] objectForKey:@"country"]];
	[_searchNameResultView setState:[[_tableEntries objectForKey:[NSString stringWithFormat:@"%d",[_table selectedRow]]] objectForKey:@"state"]];
	[_searchNameResultView fetchData];
	
	[_searchNameResultView setDelegate:self];
	[_searchNameResultView setPrevView:_actualView];
	//[_searchNameResultView setCity:searchentry];
	[_searchNameResultView initWithFrame: CGRectMake(_rect.origin.x, _rect.origin.y
													 , _rect.size.width,
													 _rect.size.height) ];
	//_previousView = [_actualView retain];
	[self setCurrentView: _searchNameResultView];
	
	//	NSLog(@"prevview: %@",[_delegate getPreviousView]);
	//	NSLog(@"actview: %@",[_delegate getCurrentView]);
	
	[_transitionView transition:1 toView:_searchNameResultView];
	
	
	
}


@end